<?php

/**
 * 处理站内消息类, 添加/查看/标注/获取列表消息
 * Class PlatMessageAction
 */
class PlatMessageAction extends Action
{
    /**
     * 保存信息
     * @param string $title 消息标题
     * @param string $message 消息内容
     * @param int $cid 登录用户
     * @param array $userId 接受用户,页面端调用'1,2,3', 内部调用[1,2,3]
     * @param int $fromUserId 发送消息的用户
     * @param int $type 消息类型 类型:0系统消息/1用户消息
     * @param int $sendType 消息类型 手机端显示信息:0系统消息/1单独设置
     * @param string $module 触发模块
     * @param string $moduleName 触发模块名称
     * @param int $priority 优先级1:优先,2:正常
     * @param int $is_send_wx 是否发送模板消息0:不发送(默认),1:发送
     * @param int $callType 优先级0:内部之间调用,1:页面端调用
     * @param string $wxMessage 不同于后台的微信消息内容(稿稿)
     * @return object
     */
    public static function pushMessage(
        $title = '',
        $message = '',
        $userId,
        $fromUserId = '',
        $type,
        $module = '',
        $moduleName = '',
        $priority = 2,
        $is_send_wx = 0,
        $callType = 0,
        $sendType=0,
        $wxMessage='',
        $customerId='',
        $url=''
    ) {
//        if(!$houjia) {
//            $retVal = Session::init();
//            if (!$retVal) {
//                Output::instance()->resultCode(code_access_denied);
//                return;
//            }
//        }

        //保存站内消息表
        $cid = Session::$user['customerId'];
        if(!empty($customerId)){
            $cid=$customerId;
        }
        Session::switchCustomer(0);
        $platMsg_table = M('plat_message');
        $platMsgUser_table = M('plat_message_user');

        $data = array();
        $data['title'] = $title;
        $data['message'] = $message;
        if ($fromUserId != null) {
            $data['fromUserId'] = $fromUserId;
        }
        if ($moduleName) {
            $data['module_name'] = $moduleName;
        }
        if ($module) {
            $data['module'] = $module;
        }
        if ($type != null) {
            $data['type'] = $type;
        }
        if ($callType) {
            $userId = explode(',', $userId);
        }
        $data['cid'] = $cid;
        $data['priority'] = $priority;
        $data['is_send_wx'] = $is_send_wx;
        $data['createTime'] = date('Y-m-d H:i:s');
        $data['updateTime'] = date('Y-m-d H:i:s');
        $data['url'] = $url;
        $msgId = $platMsg_table->data($data)->filter('strip_tags')->add();
        if (!$msgId) {
            Session::switchCustomer($cid);
            if ($callType) {
                Output::instance()->object([
                    'code' => -1,
                    'msg' => '站内消息保存失败',
                    'data' => '',
                ]);
            }
            return false;
        }
        //稿稿发送到手机端消息内容
        $wxMsgId = '';
        if($wxMessage){
            $data['message'] = $wxMessage;
            $data['sendType'] = 1;
            $data['url'] = '';
            $wxMsgId = $platMsg_table->data($data)->filter('strip_tags')->add();
            if (!$wxMsgId) {
                Session::switchCustomer($cid);
                if ($callType) {
                    //页面端调用
                    Output::instance()->object([
                        'code' => -1,
                        'msg' => '微信端消息保存失败',
                        'data' => '',
                    ]);
                }
                return false;//内部调用
            }
        }
        //保存消息用户关联表
        $sql = 'insert into wx_plat_message_user (`cid`,`messageId`,`toUserId`,`createTime`) VALUES ';
        foreach ($userId as $key => $val) {
            $sql .= "(" . $cid . "," . $msgId . "," . $val . ",'" . date('Y-m-d H:i:s') . "'),";
        }
        $sql = trim($sql, ',') . ';';
        $result = M()->execute($sql);
        if (!$result) {
            Session::switchCustomer($cid);
            if ($callType) {
                Output::instance()->object([
                    'code' => -1,
                    'msg' => '保存关联消息失败',
                    'data' => '',
                ]);
            }
            return false;
        }

        if($wxMessage){
            $wxSaveSql = 'insert into wx_plat_message_user (`cid`,`messageId`,`toUserId`,`createTime`) VALUES ';
            foreach ($userId as $key => $val) {
                $wxSaveSql .= "(" . $cid . "," . $wxMsgId . "," . $val . ",'" . date('Y-m-d H:i:s') . "'),";
            }
            $wxSaveSql = trim($wxSaveSql, ',') . ';';
            $result = M()->execute($wxSaveSql);
            if (!$result) {
                Session::switchCustomer($cid);
                Log::write('保存消息发送信息失败:' . $platMsgUser_table->getLastSql());
                if ($callType) {
                    Output::instance()->object([
                        'code' => -1,
                        'msg' => '保存微信端关联消息失败',
                        'data' => ''
                    ]);
                }
                return false;
            }
        }
        $wxCusUser_table = M('customer_user');
        if ($is_send_wx == 1) {
            //发送模板消息
            foreach ($userId as $key => $val) {
                //绑定了微信登录,发送消息
                if($wxMessage){
                    $url = C('WX_REDIRECT_HOST') . 'call.html?customerId=' . $cid . '&module=adOrder&method=messageDetail&params={"messageId":' . $wxMsgId . ',"toUserId":' . $val . '}';
                }else{
                    $url = C('WX_REDIRECT_HOST') . 'call.html?customerId=' . $cid . '&module=adOrder&method=messageDetail&params={"messageId":' . $msgId . ',"toUserId":' . $val . '}';
                }
                $userOpenid = $wxCusUser_table->where(['id'=>$val])->getField('uopenId');
                if ($userOpenid) {
                    if($customerId){
                        $fromUserName='微梦想';
                    }else{
                        $fromUserInfo = $wxCusUser_table->where(array('id' => $fromUserId))->find();
                        $fromUserName = $fromUserInfo['fullName'] ? $fromUserInfo['fullName'] : '';
                    }

                    //发送模板消息
                    $tmpStatus = 'PlatMessage_OPENTM411422542';
                    $datas['first'] = array('value' => '您有新的消息', 'color' => "#743A3A");
                    $datas['keyword1'] = array('value' => $title, 'color' => '#173177');
                    $datas['keyword2'] = array('value' => $moduleName . '-' . $fromUserName, 'color' => '#173177');
                    $datas['remark'] = array('value' => '请点击查看', "color" => '#008000');
                    TemplateMessage::send($userOpenid, $cid, $tmpStatus, $url, $datas);
                }
            }
        }

        if ($callType) {
            Output::instance()->object([
                'code' => 0,
                'msg' => 'ok',
                'data' => array(
                    'msgId' => $msgId,
                    'wxMsgId' => $wxMsgId
                )
            ]);
        }
        return false;
    }

    /**
     * 获取信息列表
     *
     * @param        $userId        用户Id, 应该来自Session里
     * @param string $type          0系统消息 1用户消息,默认所有消息
     * @param string $status        0未读 1已读,默认所有消息
     * @param int    $start         开始记录
     * @param int    $limit         每页限制
     * @param string $search        搜索条件
     * @param string $beginTime     开始时间
     * @param string $endTime       结束时间
     * @param string $order
     * @param string $by
     * @param int    $priority      优先级
     * @param string $module        下拉框模块
     * @param int    $retype        返回数据方式, 这个东西是在稿稿项目里用的
     * @param string $selectcuid
     */
    public function messageList(
        $userId,
        $module = '',
        $reType = 1,
        $start = 0,
        $limit = 10,
        $type = '',
        $status = '',
        $search = '',
        $beginTime = '',
        $endTime = '',
        $order = 'desc',
        $by = 'createTime',
        $priority = 0,
        $selectcuid = '',
        $needReturn = FALSE
    ) {
        /** 登录 */
        $retVal = Session::init();
        if (!$retVal) {
            if ($needReturn) {
                return ['code' => code_access_denied, 'msg' => '未登录'];
            }
            Output::instance()->object(code_access_denied);
            return;
        }

        /** 初始化内容 */
        $cid    = Session::$user['customerId'];
        $userId = Session::$user['id'];
        Session::switchCustomer(0);
        $platMsgUser_table          = M('plat_message_user');
        $Model_RoleModuleGroup      = M('role_module_group');
        $Model_CustomerModuleGroup  = M('customer_module_group');
        $Model_ModuleGroup          = M('module_group');
        Session::switchCustomer($cid);

        /** 筛选过滤条件 */
        $map = array();
        // 筛选对谁的消息
//        if ($reType == 1) {     // 如果==1, 表示正常项目里, toUserId为Session里的userId即可
            $map['a.toUserId'] = $userId;
//        } else {
//            $map['a.toUserId'] = array(array('eq', $userId), array('eq', $selectcuid), 'or');
//        }
        // cid区分数据
        $map['a.cid'] = $cid;
        $map['b.deleted'] = 0;
        $map['b.sendType'] = 0;
        // 参数搜索条件
        if ($search)            $map['b.title'] = ['like', '%' . $search . '%'];
        if($reType==2){
            empty($module) ? $map['b.module']=array('in','orderMessage,cashMessage,ReviewMessage,systemMessage') : $map['b.module'] = array('in',$module);
            $start=($start-1)*$limit;
        }else{
            if ($module){
                $arr_module = explode(',', $module);
                if (count($arr_module) == 0) {
                    $module = $arr_module[0];
                    $map['b.module_name'] = $module;
                } else {    // 为微梦想手机端广告消息特地改造, 传多个moduleName
                    $map['b.module_name'] = ['IN', $arr_module];
                }
            }
        }
        if ($beginTime)         $map['a.createTime'] = array('EGT', $beginTime);
        if ($endTime)           $map['a.createTime'] = array('ELT', $endTime);
        if ($type != null)      $map['b.type'] = intval($type);
        if ($status != null)    $map['a.status'] = intval($status);
        if ($priority)          $map['b.priority'] = intval($priority);

        /** 数据查询 */
        $msgList = $platMsgUser_table
            ->alias('a')
            ->field('a.*,b.fromUserId,b.module,b.message,b.type,b.deleted,b.module_name as moduleName,b.title,b.priority,b.url')
            ->join('inner join wx_plat_message b on b.id = a.messageId')
            /* ->join('left join wx_customer_user c on b.fromUserId = c.id')*/
            ->where($map)
            ->order(array('b.priority' => 'asc', 'a.' . $by => $order))
            ->limit($start, $limit)
            ->select();
        $total = $platMsgUser_table->alias('a')
            ->field('a.*,b.fromUserId,b.module,b.message,b.type,b.deleted,b.module_name as moduleName')
            ->join('inner join wx_plat_message b on b.id = a.messageId')
            ->where($map)
            ->count();

        /** 返回 */
        $dataArr = [
            'code'  => 0,
            'msg'   => 'ok',
            'data'  => $msgList
        ];
        if ($msgList) {
            if ($needReturn) {
                return [
                    'total' => $total,
                    'results' => $dataArr
                ];
            }
            Output::instance()->objArray($dataArr, $total);
        } else {
            $Out = [
                'total' => 0,
                'results' => [
                    'code' => 0,
                    'msg'  => 'ok',
                    'data' => []
                ]
            ];
            if ($needReturn) {
                return $Out;
            }

            Output::instance()->object($Out);
        }

    }

    /**
     * 获取消息详细信息
     * @param $messageId  消息id
     * @param int $toUserId 用户id
     * @param int $readType 消息阅读平台
     */
    public function messageDetail($messageId, $toUserId, $readType = 0, $needReturn = FALSE)
    {
        $retVal = Session::init();
        if (!$retVal) {
            if ($needReturn) {
                return ['code' => code_access_denied, 'msg' => '未登录'];
            }
            Output::instance()->object(code_access_denied);
            return;
        }

        //保存站内消息表
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $platMsg_table = M('plat_message_user');
        Session::switchCustomer($cid);
        $map = array();
        $map['a.messageId'] = $messageId;
        $map['a.toUserId'] = $toUserId;
        $map['a.cid'] = $cid;
        $result = $platMsg_table->alias('a')
            ->field('a.*,b.module,b.fromUserId,b.message,b.type,b.deleted,b.title,b.priority,b.module_name as moduleName')
            ->join('inner join wx_plat_message b on b.id = a.messageId')
            ->where($map)
            ->find();
        if ($result) {
            //将这一单条消息改为已读
            $bool = $platMsg_table->where(array('cid' => $cid, 'messageId' => $messageId, 'toUserId' => $toUserId))->save(array(
                'status' => 1,
                'readplat' => $readType,
                'readTime' => date('Y-m-d H:i:s')
            ));

            if (!$bool) {
                Log::write('标记消息失败-------' . $platMsg_table->getLastSql());
            }

            if ($needReturn) {
                return [
                    'code' => 0,
                    'msg' => 'ok',
                    'data' => $result
                ];
            }
            Output::instance()->object(array(
                'code' => 0,
                'msg' => 'ok',
                'data' => $result
            ));
            return;
        }
        if ($needReturn) {
            return [
                'code' => -1,
                'msg' => '读取信息失败',
                'data' => ''
            ];
        }
        Output::instance()->object(array(
            'code' => -1,
            'msg' => '读取信息失败',
            'data' => ''
        ));
    }

    /**
     * 消息标记为已读
     * @param string $messageIds 消息id数组
     * @param int $toUserId 对应的用户id
     */
    public function markMessage($messageIds, $toUserId)
    {
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->object(code_access_denied);
            return;
        }

        if (count($messageIds) == 0) {
            Output::instance()->object(array(
                'code' => -1,
                'msg' => '非法数据',
                'data' => '',
            ));
        }
        foreach (json_decode($messageIds) as $k => $val) {
            if (!is_numeric($val)) {
                Output::instance()->object(array(
                    'code' => -1,
                    'msg' => '非法数据',
                    'data' => '',
                ));
                return;
            }
        }

        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $map = array();
        $map['messageId'] = array('in', json_decode($messageIds));
        $map['toUserId'] = $toUserId;

        $platMessage_table = M('plat_message_user');
        $result = $platMessage_table->where($map)->save(array(
            'status' => 1,
            'createTime' => date('Y-m-d H:i:s')
        ));

        /*echo '<pre>';
        var_dump($platMessage_table->getDbError());
        echo '</pre>';exit;*/
        Session::switchCustomer($cid);
        if (!$result) {
            Log::write($platMessage_table->getLastSql());
            Output::instance()->object(array(
                'code' => -1,
                'msg' => '提交失败',
                'data' => '',
            ));
            return;
        }
        Output::instance()->object(array(
            'code' => 0,
            'msg' => 'ok',
            'data' => '',
        ));
    }

    /**
     * 稿稿平台个人获取消息数量
     */
    public function ggMessageNum(){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->object(code_access_denied);
            return;
        }
        Session::switchCustomer(0);
        $userId = Session::$user['id'];
        $where['a.sendType']=array('eq',0);
        $where['b.status']=array('eq',0);;
        $where['a.module']=array('eq','systemMessage');
        $where['b.toUserId']=array('eq',$userId);
        $where['a.deleted']=array('eq',0);
        $plat_message=M("plat_message as a");
        $systemCount=$plat_message->where($where)->join("wx_plat_message_user as b on a.id=b.messageId")->count();

        $where['a.module']=array('in','orderMessage,cashMessage,ReviewMessage');
        $orderCount=$plat_message->where($where)->join("wx_plat_message_user as b on a.id=b.messageId")->count();
        $res["orderCount"]=$orderCount;
        $res["systemCount"]=$systemCount;
        $res["total"]=$systemCount+$orderCount;
        Output::instance()->object($res);


    }

    /**
     * 删除消息
     * @param array $messageIds 消息ID数组
     * @param int $toUserId 哪位用户
     * return object
     */
    /*public function deleteMessage($messageIds = array(), $toUserId){
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->object(code_access_denied);
            return;
        }

        if(count($messageIds) == 0){
            Output::instance()->object(array(
                'code' => -1,
                'msg' => '非法数据',
                'data' => '',
            ));
        }
        foreach($messageIds as $k=>$val){
            if(!is_numeric($val)){
                Output::instance()->object(array(
                    'code' => -1,
                    'msg' => '非法数据',
                    'data' => '',
                ));
                return;
            }
        }

        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $map = array();
        $map['messageId'] = array('in', $messageIds);
        $map['toUserId'] = $toUserId;

        $platMessage_table = M('plat_message');
        $result = $platMessage_table->where($map)->save(array('deleted'=>1));
        Session::switchCustomer($cid);
        if(!$result){
            Log::write($platMessage_table->getLastSql());
            Output::instance()->object(array(
                'code' => -1,
                'msg' => '修改失败',
                'data' => '',
            ));
            return;
        }
        Output::instance()->object(array(
            'code' => 0,
            'msg' => 'ok',
            'data' => '',
        ));
    }*/

    /**
     * 删除消息
     * @param array $messageId 消息ID
     */
    public function deleteMessage($messageId){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->object(code_access_denied);
            return;
        }
        Session::switchCustomer(0);
        $plat_message=M('plat_message');
        $result=$plat_message->where("id=$messageId")->setField('deleted',1);
        if($result){
            Output::instance()->resultCode(code_success);
        }else{
            Output::instance()->resultCode(code_sql_error);
        }

    }
}
